import React, { useState, useEffect, useCallback } from 'react';
import { InputNumber, Button, List, Typography, Divider, Popconfirm } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import GoodsWithSubGoodsSelector, { GoodsItem, SelectedGoodsItem } from './GoodsWithSubGoodsSelector';

const { Text } = Typography;

interface GoodsQuantityItem extends GoodsItem {
    quantity: number;
}

interface GoodsQuantitySelectorProps {
    value?: GoodsQuantityItem[];
    onChange?: (value: GoodsQuantityItem[]) => void;
    placeholder?: string;
    style?: React.CSSProperties;
    disabled?: boolean;
    id?: string;
}

const GoodsQuantitySelector: React.FC<GoodsQuantitySelectorProps> = ({
                                                                         value = [],
                                                                         onChange,
                                                                         placeholder = '搜索商品或子商品...',
                                                                         style,
                                                                         disabled = false,
                                                                         id,
                                                                     }) => {
    const selectedItems = value
    const [selectedGoodsData, setSelectedGoodsData] = useState<GoodsItem[]>([]);
    useEffect(() => {
        console.log("GoodsQuantitySelector onChange change")
        return ()=>{
            console.log("GoodsQuantitySelector onChange destroy")
        }
    }, []);

    // 处理商品选择变化
    const handleGoodsSelect = useCallback((uSelectedItems: GoodsItem[]) => {

        // 过滤掉已存在的商品
        const newSelectedItems = uSelectedItems.map(it=>{
            let old = selectedItems.find(item=>item.subGoodsId===it.subGoodsId && item.id===it.id);
            if(old){
                return old
            }else {
                return {
                    ...it,
                    quantity: 1,
                }
            }
        })

        if (onChange) onChange(newSelectedItems);
    }, [selectedItems, onChange]);

    // 更新商品数量
    const updateQuantity = useCallback((index: number, quantity: number) => {
        const updatedItems = [...selectedItems];
        updatedItems[index] = { ...updatedItems[index], quantity };
        if (onChange) onChange(updatedItems);
    }, [selectedItems, onChange]);

    // 删除商品
    const removeItem = useCallback((index: number) => {
        const itemToRemove = selectedItems[index];
        const updatedItems = selectedItems.filter((_, i) => i !== index);

        // 同时从商品数据中移除
        setSelectedGoodsData(prev =>
            prev.filter(item => getItemKey(item) !== getItemKey(itemToRemove))
        );

        if (onChange) onChange(updatedItems);
    }, [selectedItems, onChange]);

    // 获取商品的唯一键
    const getItemKey = (item: SelectedGoodsItem | GoodsItem) => {
        return `${item.id}-${item.subGoodsId || ''}`;
    };

    // 查找商品信息
    const findGoodsInfo = useCallback((item: SelectedGoodsItem): GoodsItem | undefined => {
        return selectedGoodsData.find(g => getItemKey(g) === getItemKey(item));
    },[selectedGoodsData]);
    return (

        <div style={style}>
             {/*商品选择器 - 直接使用 GoodsSelector 的选择功能 */}
            <GoodsWithSubGoodsSelector
                id={id}
                mode="multiple"
                onChange={handleGoodsSelect}
                placeholder={placeholder}
                disabled={disabled}
                style={{ width: '100%' }}
                value={value}
            />

            <Divider />

            {/* 已选商品列表 */}
            {selectedItems.length > 0 && (
                <List
                    size="small"
                    bordered
                    dataSource={selectedItems}
                    renderItem={(item, index) => {
                        const goodsInfo = findGoodsInfo(item);

                        return (
                            <List.Item
                                actions={[
                                    <InputNumber
                                        min={1}
                                        max={10000}
                                        value={item.quantity}
                                        onChange={(value) => updateQuantity(index, value || 1)}
                                        disabled={disabled}
                                    />,
                                    <Popconfirm
                                        title="确定要删除吗？"
                                        onConfirm={() => removeItem(index)}
                                        disabled={disabled}
                                    >
                                        <Button
                                            type="text"
                                            icon={<DeleteOutlined />}
                                            disabled={disabled}
                                        />
                                    </Popconfirm>
                                ]}
                            >
                                <List.Item.Meta
                                    title={goodsInfo?.name || `商品ID: ${item.id}`}
                                    description={
                                        <>
                                            {goodsInfo && (
                                                <>
                                                    <Text type="secondary">条码: {goodsInfo.barcode}</Text>
                                                    {goodsInfo.subGoodsNumber && (
                                                        <Text type="secondary"> | 子商品编号: {goodsInfo.subGoodsNumber}</Text>
                                                    )}
                                                    <br />
                                                </>
                                            )}
                                            <Text type="secondary">数量: {item.quantity}</Text>
                                        </>
                                    }
                                />
                            </List.Item>
                        );
                    }}
                />
            )}

            {selectedItems.length === 0 && !disabled && (
                <div style={{ textAlign: 'center', padding: '12px', color: '#999' }}>
                    请从上方选择商品
                </div>
            )}
        </div>
    );
};

export default GoodsQuantitySelector;